package com.twu.biblioteca.view;

import com.twu.biblioteca.events.Event;
import com.twu.biblioteca.events.Listener;
import com.twu.biblioteca.model.users.exceptions.InvalidUsernameException;
import com.twu.biblioteca.model.users.Username;
import com.twu.biblioteca.presenter.LoginPresenter;
import com.twu.biblioteca.view.utils.Input;
import com.twu.biblioteca.view.utils.Output;

import java.io.InputStream;
import java.io.PrintStream;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * User: cschlumb
 * Date: 09/08/2013
 * Time: 15:17
 * To change this template use File | Settings | File Templates.
 */
public class LoginView implements LoginPresenter.Display{

    private final Input inputStream;
    private final Output printStream;
    private String username;
    private String password;

    private Event userDetailsEvent = new Event();

    public LoginView(Output printStream, Input inputStream) {
        this.inputStream = inputStream;
        this.printStream = printStream;
    }

    @Override
    public void prompt(){
        promptUsername();
        promptPassword();
        userDetailsEvent.fire();
    }

    void promptUsername(){
        printStream.write("Please input username:");
        username = inputStream.readString();
    }

    void promptPassword(){
        printStream.write("Please input password:");
        password = inputStream.readString();
    }

    @Override
    public String getPassword(){
        return password;
    }

    @Override
    public Username getUsername() throws InvalidUsernameException {
        return Username.valueOf(username);
    }

    @Override
    public void successMessage() {
        printStream.write("Successfully logged in.");
    }

    @Override
    public void failureMessage() {
        printStream.write("Error: Invalid user credentials.");
    }

    @Override
    public void addEventListener(Listener listener) {
        userDetailsEvent.addListener(listener);
    }
}
